/* eslint-disable react-native/no-inline-styles */
import React, {Component} from 'react';
import {
  View,
  Text,
  Dimensions,
  StyleSheet,
  ScrollView,
  TouchableHighlight,ToastAndroid,Alert
} from 'react-native';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import {ECharts} from 'react-native-echarts-wrapper';
import {Accordion, List, ActivityIndicator} from '@ant-design/react-native';
import moment from 'moment';
import {cwGet} from '../utils/http';

export default class NowDataPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentTab: 'now',
      animating: false,
      animating1: false,
      title: '',
        currentDeviceForList: global.nowDevice.id,
      colors: [
        '#C53D1C',
        '#374C5A',
        '#61A0A8',
        '#D48265',
        '#91C7AF',
        '#749F83',
        '#CA8622',
        '#BDA29A',
        '#6E7074',
        '#546570',
      ],
      leftTitle: '',
      rightTitle: '',
      deviceList: [],
      currentDevice: '',
      //currentDeviceForList: '',
      legends: [],
      saveData: {},
      series: [],
      childTag: [],
      tagValues: [],
      tableData: [],
      yAxis: [],
      activeSections: [],
      currentTime: '',
        isLoad2Hour:true,//05-04
      tabList: [
        {label: '曲线图', tag: 'now'},
        {label: '全部数据', tag: 'all'},
      ],
    };
      //this.isLoad2Hour=true;//05-04
  }

  componentDidMount() {
    this.time = null;
    this.time2 = null;

    this.setState(
      {
        leftTitle: global.nowDevice.name,
        title: global.nowDevice.name,
        currentDevice: global.nowDevice.id,
        legends: [],
        saveData: {},
        series: [],
      },
      () => {
        this.getDeviceTag();
      },
    );
    this.setState(
      {
        rightTitle: global.nowDevice.name,
        title: global.nowDevice.name,
        currentDeviceForList: global.nowDevice.id,
      },
      () => {
         this.getAllTag();
      },
    );
  }

  componentWillUnmount() {
    clearInterval(this.time);
    clearTimeout(this.time2);
    clearTimeout(this.time3);
    this.time = null;
    this.time2 = null;
    this.time3 = null;
  }

  onChange(activeSections) {
    this.setState({activeSections});
  }

  getDeviceTag() {
    clearInterval(this.time);
    this.time = null;
    const {currentDevice} = this.state;
    if (currentDevice) {
      cwGet('History/GetChartTags' + '?deviceID=' + currentDevice).then(
        string => {
          console.log('aaaaaaaaaaaaaaaa', string);
          if (string.length) {
            const tags = string.map(item => item.tag);

            this.setState({
              legends: string.map(v => {
                return v.tagChartName;
              }),
              animating: true,
            });
            this.time = setInterval(() => {
                this.getChartData(tags.join('|'));
            }, 5000);
          }
        },
      );
    } else {
      this.setState({
        series: [],
      });
      clearInterval(this.time);
      this.time = null;
    }
  }

  getChartData=(tagString)=> {
     //this.isLoad2Hour = false;
    //console.warn('getChartData',this.isLoad2Hour)
      const {saveData, colors, legends,currentDeviceForList,timeData,isLoad2Hour,allValues1} = this.state;//yAxis =[]
      let chartStartTime =moment().subtract(2, 'hours').format('YYYY-MM-DD HH:mm:ss');
      let chartEndTime =moment().format('YYYY-MM-DD HH:mm:ss');
      let strurl = 'History/GetHistoryDataByMoreSteps?tags=' +
          tagString +
          '&startTime=' +
          encodeURIComponent(chartStartTime) +
          '&endTime=' +
          encodeURIComponent(chartEndTime);

        if (isLoad2Hour === false){
            strurl ='RealTime/GetRealTimeData?tag=' + tagString;
        }
        // console.warn(strurl);
        if (isLoad2Hour === true){
            cwGet(strurl).then(
                async data=>{
                   //this.isLoad2Hour = false;
                   // console.warn('zhy',strurl,data);
                   if (data.length) {
                       let r = await cwGet(
                           'History/GetChartTags?deviceID=' + currentDeviceForList,
                       );
                       //this.state.animating= false;
                       //this.setState({animating:false});
                       //组装数据
                       var first = data[0];
                       //console.warn("zhy2","first",first);
                       var firstTag = first.tagChartName;
                       //console.warn("zhy2","firstTag",firstTag);
                       var firstData = data.filter(function(item) {
                           if (item.tagChartName == firstTag) {
                               return item.time;
                           }
                       });
                       //console.warn("zhy2","firstData",firstData);
                       //x轴数据
                       var timeData = firstData.map(item => {
                          /* let items = item.time.split(' ')[1];
                           let itemsarr = items.split(':')
                           return itemsarr[2]+":"+itemsarr[1]+":"+itemsarr[0];*/
                           return item.time.split(' ')[1];
                       });
                       var timeData2 = firstData.map(item => {
                           return item.time;
                       });
                       //console.warn("zhy2","timeData",timeData);//timeData--->timeData
                       //console.warn("zhy2","timeData2",timeData2);//timeData2--->timeData
                       //有多少条曲线
                       var allTags = r.map(v => v.tagChartName);
                       //console.warn("zhy2","allTags",allTags);

                       var allValues = [];
                       var izhy =0;
                       var saveData1 = {};
                       var tableData1 = [];
                       allTags.map(item => {   //allTags-->legends
                           var tagValue = data.filter(function(d) {
                               return d.tagChartName == item;
                           });
                           //console.warn("zhy2","tagValue",tagValue);

                           if (tagValue.length > 0) {
                               var lowAxis = tagValue[0].lowAxis;
                               var highAxis = tagValue[0].highAxis;
                               allValues.push({
                                   name: item,
                                   value: tagValue,
                                   lowAxis: lowAxis,
                                   highAxis: highAxis,
                               });

                               tagValue.map(item =>{
                                   if (!saveData1[item.tag]) {
                                       saveData1[item.tag] = {
                                           name: item.tagChartName,
                                           type: 'line',
                                           color: colors[izhy],
                                           smooth: false,
                                           xAxisIndex: 0,
                                           yAxisIndex: izhy,
                                           data: [],
                                       };
                                       saveData1[item.tag].data.push(item.value * 1);
                                       tableData1.push({
                                           name: item.tagChartName,
                                           value: item.value * 1,
                                           color: colors[izhy],
                                       });
                                   }
                                   else{
                                       saveData1[item.tag].data.push(item.value * 1);
                                       tableData1.push({
                                           name: item.tagChartName,
                                           value: item.value * 1,
                                           color: colors[izhy],
                                       });
                                   }
                               })

                           }
                           //console.warn("zhy2","allValues",allValues);
                           izhy = izhy+1;
                       });
                       //console.warn("zhy2","allValues[总数]",allValues);
                       const series1 = Object.values(saveData1);

                       var seriesData = [];
                       var i = 0;
                       allValues.map(item => {
                           seriesData.push({
                               symbol: 'none', //去掉圆点
                               name: item.name,
                               type: 'line',
                               data: item.value,
                               yAxisIndex: i,
                               animation: false,
                               lineStyle: {
                                   width: 1,
                               },
                           });
                           ++i;
                           //console.warn("zhy2","seriesData",seriesData);
                       });
                       //console.warn("zhy2","seriesData[总数]",seriesData);

                       var yAxisData = [];
                       var j = 0;
                       var count = allValues.length;
                       var avg = count / 2;
                       var offset = -80;
                       var position = 'left';
                       allValues.map(item => {
                           if (j == avg) {
                               offset = -80;
                               position = 'right';
                           }
                           offset += 80;
                           yAxisData.push({
                               show: false,
                               name: item.name,
                               type: 'value',
                               max: parseInt(item.highAxis),
                               min: parseInt(item.lowAxis),
                               position: position,
                               offset: offset,
                           });
                           j++;
                           //console.warn("zhy2","yAxisData",yAxisData);
                       });
                       //console.warn("zhy2","yAxisData[总数]",yAxisData);
                       this.setState(
                           {
                               saveData:saveData1, //按类分数据集合(每个类)saveData1
                               legends:allTags,  //图例allTags
                               series:series1,   //数据序列series1
                               //tableData:tableData1,//按类分数据集合（大类合集）tableData1
                               animating: false,
                               isLoad2Hour:false,
                               allValues1:allValues,
                               timeData:timeData
                           },
                           () => {
                               //echarts中获取数据的option设置
                               const optionDatas = {
                                   tooltip: {
                                       trigger: 'axis',
                                       axisPointer: {
                                           type: 'line',
                                           animation: false,
                                           label: {
                                               backgroundColor: '#505765',
                                           },
                                       },
                                       confine: true,
                                   },

                                   legend: {
                                       data: allTags,
                                       padding:[0,2],
                                       itemGap:5,
                                       itemHeight:10,
                                       textStyle: {
                                           fontSize: 12,
                                       }
                                   },
                                   xAxis: [
                                       {
                                           textSize: 10,
                                           type: 'category',
                                           boundaryGap: false,
                                           axisLine: {onZero: false},
                                           axisLabel:{
                                               interval: 100000,
                                               showMinLabel: true,
                                               showMaxLabel: true,
                                               textStyle: {
                                                   color: '#999',
                                                   fontSize: 10,
                                               }
                                           },
                                           data: timeData,//[timeData[0],timeData[timeData.length/2],timeData[timeData.length-1]],
                                       },
                                   ],
                                   yAxis:yAxisData,
                                   series: series1,
                               };
                               this.Echart.setOption(optionDatas);
                           }
                       );

                   }
             else {
                ToastAndroid.show('暂无数据', ToastAndroid.SHORT);
              }
                })
                .finally(() => {
                    this.setState({
                        animating: false,
                    });
                });

        }
        else{
            cwGet(strurl)
                .then(data => {
                    //console.log(data);
                    // console.warn('zhy',strurl,data);
                    // const yAxis1 = yAxis;
                    const yAxis = [] ;
                    const tableData = [];
                    var series ={} ;
                        timeData.shift();
                    //timeData.push(data[0].time.split(' ')[1]);
                    /*let items  =data[0].time.split(' ')[1] ;
                    let itemsarr = items.split(':')
                    let timess = itemsarr[2]+":"+itemsarr[1]+":"+itemsarr[0];*/
                    let timess  =data[0].time.split(' ')[1] ;
                    let isAdd = true;
                    timeData.map(item=> {
                        if (item === timess){
                            isAdd = false;
                        }
                    })
                    if (isAdd){
                        timeData.push(timess);
                        // console.warn('zhy99',timeData)
                        for (var i = 0; i < data.length; i++) {
                            //console.warn('zhy66',data[i].time)
                            //console.warn("zhy1","data["+i+"]===",data[i]);
                            yAxis.push({
                                type: 'value',
                                max: data[i].highAxis || 2000,
                                min: data[i].lowAxis || 0,
                            });
                            var lowAxis =  data[i].lowAxis;
                            var highAxis =  data[i].highAxis;

                            allValues1.push({
                                name: data[i].tagChartName,
                                value: data,
                                lowAxis: lowAxis,
                                highAxis: highAxis,
                            });

                            //console.warn("zhy1","yAxis===",yAxis);
                            // legends.push(data[i]['tagChartName']);
                            if (!saveData[data[i]['tag']]) {
                                saveData[data[i]['tag']] = {
                                    name: data[i].tagChartName,
                                    type: 'line',
                                    color: colors[i],
                                    smooth: false,
                                    xAxisIndex: 0,
                                    yAxisIndex: i,
                                    data: [],
                                };
                                saveData[data[i]['tag']].data.push(data[i].value * 1);
                                //console.warn("zhy1",data[i]['tag'],saveData);
                                tableData.push({
                                    name: data[i].tagChartName,
                                    value: data[i].value * 1,
                                    color: colors[i],
                                });
                                //console.warn("zhy1","tableData",tableData);
                            } else {
                                if (saveData[data[i]['tag']].data.length >= 1440) {//=== 50 1440 720
                                    saveData[data[i]['tag']].data.shift();
                                    saveData[data[i]['tag']].data.push(data[i].value * 1);
                                } else {
                                    saveData[data[i]['tag']].data.push(data[i].value * 1);
                                }
                                //console.warn("zhy1",data[i]['tag'],saveData);
                                tableData.push({
                                    name: data[i].tagChartName,
                                    value: data[i].value * 1,
                                    color: colors[i],
                                });
                                //console.warn("zhy1","tableData",tableData);
                            }
                        }
                        series = Object.values(saveData);
                        //console.warn("zhy1","series",series);
                        var yAxisData = [];
                        var j2 = 0;
                        var count = allValues1.length;
                        var avg = count / 2;
                        var offset2 = -80;
                        var position = 'left';
                        allValues1.map(item => {
                            if (j2 == avg) {
                                offset2 = -80;
                                position = 'right';
                            }
                            offset2 += 80;
                            yAxisData.push({
                                show: false,
                                name: item.name,
                                type: 'value',
                                max: parseInt(item.highAxis),
                                min: parseInt(item.lowAxis),
                                position: position,
                                offset: offset2,
                            });
                            j2++;
                            //console.warn("zhy2","yAxisData",yAxisData);
                        });
                        //console.warn("zhy2","yAxisData[总数]",yAxisData);
                    }

                    this.setState(
                        {
                            saveData, //按类分数据集合(每个类)
                            legends,  //图例
                            series,   //数据序列
                            //tableData,//按类分数据集合（大类合集）
                            //yAxis,    //Y轴
                            animating: false,
                            allValues1,
                            timeData:timeData,
                        },
                        () => {
                            // console.log('hahahah', this.state.tableData);
                            this.Echart.setOption({
                                tooltip: {
                                    trigger: 'axis',
                                    axisPointer: {
                                        type: 'line',
                                        animation: false,
                                        label: {
                                            backgroundColor: '#505765',
                                        },
                                    },
                                    confine: true,
                                },
                                /*grid: [
                                    {
                                        x: '0%',
                                        y: '20%',
                                        width: '100%',
                                        height: '60%',
                                        tooltip: {
                                            axisPointer: {
                                                type: 'line',
                                            },
                                        },
                                    },
                                ],*/
                                legend: {
                                    data: legends,
                                    padding:[0,2],
                                    itemGap:5,
                                    itemHeight:10,
                                    textStyle: {
                                        fontSize: 12,
                                    }
                                },
                                /*dataZoom: {
                                    show: false,
                                    start: 0,
                                    end: 100,
                                },*/
                                xAxis: [
                                    {
                                        // splitLine: {
                                        //     show: true
                                        // },
                                        // axisLine: {
                                        //     show: false
                                        // },
                                        //min:timeData[0],
                                        //max:timeData[timeData.length-1],
                                        textSize: 5,
                                        type: 'category',
                                        boundaryGap: false,
                                        axisLine: {onZero: false},
                                        axisLabel:{
                                            interval: 100000,
                                            showMinLabel: true,
                                            showMaxLabel: true,
                                            textStyle: {
                                                color: '#999',
                                                fontSize: 10,
                                            }
                                        },
                                        data: timeData,//[timeData[0],timeData[timeData.length/2],timeData[timeData.length-1]],
                                        /*data: (function() {
                                            var now = new Date();
                                            var res = [];
                                            var len =10 ;//10 gai 1440
                                            while (len--) {
                                                res.unshift(now.toLocaleTimeString().replace(/^\D*!/, ''));
                                                now = new Date(now - 2000);
                                            }
                                            return res;
                                        })(),*/
                                    },
                                ],
                                yAxis: yAxisData || [],//yAxis
                                series: series || [],
                            });
                        },
                    );
                })
                .catch(err => {
                    console.warn("zhy000",err)
                    this.setState({
                        animating: false,
                    });
                    clearInterval(this.time2);
                    clearInterval(this.time);
                    this.time = null;
                    Alert.alert('实时数据获取异常，请稍候再试');
                });
        }


  }

  getAllTag() {
    clearInterval(this.time3);
    if (!this.state.currentDeviceForList) {
      this.setState({
        tagValues: [],
        currentTime: '',
      });
      return;
    }
    this.time3 = null;
    cwGet(
      'RealTime/GetDeviceTags?deviceID=' + this.state.currentDeviceForList,
    ).then(res => {
      console.log('allTag', res);
      var childTag = [];
      if (res.deviceItems.length) {
        for (let item of res.deviceItems) {
          var obj = {
            deviceItemID: item['deviceItemID'],
            deviceItemName: item['deviceItemName'],
            deviceItemTags: item['deviceItemProperties'].map(item => {
              if (item.tag) {
                return item.tag;
              } else {
                return '';
              }
            }),
            tagValues: [],
          };
          childTag.push(obj);
        }
      }
      var tags = [];
      for (let item of childTag) {
        tags.push(...item['deviceItemTags']);
      }
      tags = tags.filter(item => item);
      var tagString = tags.join('|');
      const that = this;
      this.setState({
        animating1: true,
      });
      that.time3 = setInterval(() => {
        cwGet('RealTime/GetRealTimeDataByMoreSteps?tags=' + tagString)
          .then(data => {
            if (data.length) {
              this.setState({
                animating1: false,
              });
              console.log(data);
              for (let child of childTag) {
                const tempData = [];
                for (let item of data) {
                  if (child.deviceItemTags.includes(item.tag)) {
                    tempData.push(item);
                  }
                }
                child.tagValues = [].concat([], tempData);
              }
              console.log(childTag);
              this.setState(
                {
                  currentTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                  tagValues: childTag,
                  animating1: false,
                },
                () => {
                  console.log(this.state.tagValues);
                },
              );
            }
          })
          .catch(err => {
            this.setState({
              animating1: false,
            });
            clearInterval(this.time3);
            this.time3 = null;
          });
      }, 2000);
    });
  }

  /*getTagValuesList(tagString) {
    const that = this;
    console.log('getTagValuesList');
    cwGet('RealTime/GetRealTimeDataByMoreSteps?tags=' + tagString)
      .then(data => {
        if (data.length) {
          console.log(data);
          for (let item of data) {
            for (let child of childTag) {
              if (child.deviceItemTags.includes(item.tag)) {
                child.tagValues.push(item);
              }
            }
          }
          this.setState(
            {
              tagValues: childTag,
            },
            () => {
              console.log(this.state.tagValues);
            },
          );
        }
      })
      .catch(err => {
        clearInterval(this.time3);
        that.time3 = null;
      });
  }*/

  onTabClick(e) {
    let title = '';
    if (e === 'now') {
      title = this.state.leftTitle;
    } else {
      title = this.state.rightTitle;
    }
    this.setState({
      currentTab: e,
      title,
    });
  }

  defineList(rowData, rowID, highlighted) {
    return <Text style={{padding: 10}}>{rowData.name}</Text>;
  }

  render() {
    const deviceWidth = Dimensions.get('window').width;
    const {legends, series, yAxis, currentTab, tableData} = this.state;
    return (
      <ScrollView height={'100%'}>
        <View
          style={{
            marginLeft: 20,
            flexDirection: 'row',
            marginTop: 5,
            alignItems: 'center',
          }}>
          <FontAwesome
            style={{backgroundColor: 'transparent', marginRight: 20}}
            name="bars"
            color="grey"
            size={16}
          />
          <Text style={{fontSize: 16}}>实时数据</Text>
          {global.nowDevice.name.length > 0 ? (
            <FontAwesome
              style={{
                backgroundColor: 'transparent',
                marginRight: 10,
                marginLeft: 10,
              }}
              name="chevron-left"
              color="grey"
              size={16}
            />
          ) : (
            <View></View>
          )}
          <Text>{global.nowDevice.name}</Text>
        </View>
        <View style={{flexDirection: 'row', width: '100%'}}>
          {this.state.tabList.map(item => {
            return (
              <TouchableHighlight
                underlayColor={'#fff'}
                key={item.id}
                style={{
                  flex: 1,
                  flexDirection: 'row',
                  justifyContent: 'center',
                  paddingTop: 4,
                  paddingBottom: 4,
                  marginTop: 5,
                }}
                onPress={this.onTabClick.bind(this, item.tag)}>
                <View
                  style={[
                    {width: '85%', backgroundColor: '#D5D6D8'},
                    currentTab === item.tag ? NowDataStyles.curretnTab : '',
                  ]}>
                  <Text
                    style={{fontSize: 16, textAlign: 'center', color: '#fff'}}>
                    {item.label}
                  </Text>
                </View>
              </TouchableHighlight>
            );
          })}
        </View>
        <View style={{display: currentTab === 'now' ? 'flex' : 'none'}}>
          <View style={{height: 550, paddingHorizontal: 4}}>
            <ECharts
                style={{flex:1}}
              ref={ref => {
                this.Echart = ref;
              }}
              option={{}}
            />
          </View>
          <ActivityIndicator
            animating={this.state.animating}
            toast
            size="large"
            text="加载中..."
          />
          <View
            style={{
              flexDirection: 'row',
              flexWrap: 'wrap',
              paddingLeft: 20,
              paddingRight: 20,
            }}>
            {tableData.length > 0 &&
              tableData.map(item => {
                return (
                  <View
                    style={{
                      width: '50%',
                      float: 'left',
                      flexDirection: 'row',
                      paddingTop: 4,
                      paddingBottom: 2,
                    }}>
                    <Text
                      style={{
                        width: '50%',
                        textAlign: 'center',
                        color: item.color,
                      }}>
                      {item.name}
                    </Text>
                    <Text
                      style={{
                        width: '50%',
                        textAlign: 'center',
                        color: item.color,
                      }}>
                      {item.value}
                    </Text>
                  </View>
                );
              })}
          </View>
        </View>
        <View style={{display: currentTab === 'all' ? 'flex' : 'none'}}>
          {this.state.currentTime.length ? (
            <Text style={{fontSize: 14, marginLeft: 20, width: '100%'}}>
              {this.state.currentTime}
            </Text>
          ) : (
            <View />
          )}
          <ActivityIndicator
            style={{marginTop: 100}}
            animating={this.state.animating1}
            toast
            size="large"
            text="加载中..."
          />
          <ScrollView style={{height: Dimensions.get('window').height - 220}}>
            {this.state.tagValues.length ? (
              <Accordion
                onChange={this.onChange.bind(this)}
                activeSections={this.state.activeSections}>
                {this.state.tagValues.map(item => {
                  return (
                    <Accordion.Panel
                      style={{
                        backgroundColor: '#5B8DD2',
                        paddingTop: 5,
                        paddingBottom: 5,
                        flexDirection: 'row',
                        marginBottom: 2,
                        justifyContent: 'space-between',
                      }}
                      header={
                        <Text
                          style={{fontSize: 14, color: '#fff', marginLeft: 5}}>
                          {item.deviceItemName}
                        </Text>
                      }>
                      <View>
                        <List>
                          {item.tagValues.length ? (
                            item.tagValues.map(item => {
                              return (
                                <List.Item wrap multipleLine extra={item.value}>
                                  <Text style={{fontSize: 14}}>
                                    {item.signNo}
                                  </Text>
                                </List.Item>
                              );
                            })
                          ) : (
                            <List.Item />
                          )}
                        </List>
                      </View>
                    </Accordion.Panel>
                  );
                })}
              </Accordion>
            ) : (
              <></>
            )}
          </ScrollView>
        </View>
      </ScrollView>
    );
  }
}

const NowDataStyles = StyleSheet.create({
  nextTab: {
    borderWidth: 1,
    borderColor: '#E8C1C1',
    backgroundColor: '#F4F4F4',
    color: '#B2B2B2',
  },
  curretnTab: {
    backgroundColor: '#638AD0',
  },
});
